import {Component, Input} from "@angular/core";
import {UserActionService, UserGroupActionReq} from "@core/service/UserActionService";
import {NzMessageService} from "ng-zorro-antd/message";
import {BBYUtils} from "@shared/utils/BBYUtils";
interface UserView{
  checked: boolean;
  username:string
  userId:string
}
@Component({
  selector: 'bby-search-user-card',
  styleUrls:['./search-user-card.scss'],
  templateUrl:'./search-user-card.html'
})
export class SearchUserCard{

  loading = false;
  data: UserView[] = [];
  @Input()
  contentIdSet=new Set<string>();
  @Input()
  groupId=''
  searchValue='';
  lastValueChange:number=0
  constructor(
    private userActionService:UserActionService,
    private message: NzMessageService
  ) {
    this.contentIdSet.add('623de41c36e7e045ad4238fd')
    this.data.forEach(user=>user.checked=this.contentIdSet.has(user.userId))
  }

  interval_cnt=0;
  interval:any
  searchFocusin(){
    clearInterval(this.interval)
    this.interval = setInterval(()=>{
      if (this.interval_cnt>0){
        this.search()
        this.interval_cnt=-60;
      }else {
        this.interval_cnt++;
      }
    },500)
  }
  searchFocusout(){
    clearInterval(this.interval)
  }
  inputChange() {
    this.interval_cnt=0;
  }

  userCheckedChange(item:UserView) {
    console.log(item)
    this.loading=true;
    let option :UserGroupActionReq = {
      opera:item.checked? 'addUser':'deleteUser',
      userId:item.userId,
      groupId:this.groupId
    }
    BBYUtils.handelResult(
      this.userActionService.setUserGroups(option),
      res => {
        console.log(res.data)
        this.loading=false;
      },res => {
        this.message.error(res.msg)
        item.checked=!item.checked;
        this.loading=false;
      }
    )
  }

  search() {
    if (this.searchValue==''){
      return;
    }
    this.loading=true;
    BBYUtils.handelResult(
      this.userActionService.searchUser(this.searchValue),
      res => {
        console.log(res.data)
        // let data:UserView[] = res.data
        for (let user of res.data){
          user.checked=this.contentIdSet.has(user.from)
        }
        this.data=res.data
        this.loading=false;
      },res => {
        this.message.error(res.msg)
        this.loading=false;
      }
    )
  }
}
